<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\ActivityCategory;
use plugin\admin\app\model\WorshipSurname;
use support\Request;
use support\Response;
use plugin\admin\app\model\WorshipSurnameCategory;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 姓氏分类 
 */
class WorshipSurnameCategoryController extends Crud
{
    
    /**
     * @var WorshipSurnameCategory
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new WorshipSurnameCategory;
    }

    public function get(): Response
    {
        return $this->json(0, 'ok', WorshipSurnameCategory::list());
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('worship-surname-category/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {

            $data = parent::insert($request);

            $innerData = json_decode($data->rawBody(), true);

            WorshipSurname::insert([
                'category_id' => $innerData['data']['id'],
                'name' => $request->post('name'),
                'desc' => $request->post('desc'),
                'thumb' => $request->post('thumb'),
                'is_enable' => 1,
                'is_default' => 1,
            ]);

            return $data;
        }
        return view('worship-surname-category/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $worshipSurname = WorshipSurname::where('category_id', $request->post('id'))->whereNull('user_id')->first();

            if (!$worshipSurname) {
                $worshipSurname = new WorshipSurname();
                $worshipSurname['category_id'] = $request->post('id');
                $worshipSurname['is_enable'] = 1;
            }

            $worshipSurname['name'] = $request->post('name');
            $worshipSurname['thumb'] = $request->post('thumb');
            $worshipSurname['desc'] = $request->post('desc');
            $worshipSurname->save();


            return parent::update($request);
        }
        return view('worship-surname-category/update');
    }

}
